package com.edu.hre.struts.action.admin;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.ComboBoxInit;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreCompensation;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.admin.CompensationUpdateForm;
import com.edu.hre.struts.form.admin.PayrollForm;

public class CompensationUpdateAction extends DispatchAction{
	
	private static final Logger logger = Logger.getLogger(CompensationUpdateAction.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private final String ACTION_NAME = "compensationUpdate";
	
	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		CompensationUpdateForm beanForm = (CompensationUpdateForm) form;
		beanForm.setIsAddNew(true);

		if(request.getParameter(StringConstants.BTN_ADD) == null){
			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}  
		
		String message = validateForm(beanForm);
		if(!StringUtils.isBlank(message)){
			beanForm.setMessage(message);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		int year = 0;
		try {
			
			year = Integer.parseInt(beanForm.getYear());
		} catch (Exception e) {

		}
		
		HreCompensation tmpCom = baseService.getFirstPojoAnd(new String[]{"year", "month"}, new int[]{Compare.EQUAL, Compare.EQUAL}, new Object[]{year, beanForm.getMonth()}, HreCompensation.class);
		if (tmpCom != null) {
			beanForm.setMessage("The compensation for this month has been added already!");
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		HreCompensation tmp = new HreCompensation();
		tmp.setMonth(beanForm.getMonth());
		tmp.setYear(CommonUtils.parseInt(beanForm.getYear(), 0));
		tmp.setAmount(Double.parseDouble(beanForm.getAmount()));
		tmp.setDateCreated(new Date());
		tmp.setDateModified(new Date());

		boolean status = baseService.saveOrUpdate(tmp);
		if (!status) {
			beanForm.setMessage(StringConstants.INSERT_FAILURE_MESSAGE);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		response.getWriter().write(StringConstants.POP_UP_CLOSE_SCRIPT);
		return null;
	}
	
	public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		CompensationUpdateForm beanForm = (CompensationUpdateForm) form;
		beanForm.setIsAddNew(false); 

		if(request.getParameter(StringConstants.BTN_EDIT) == null){

			int id = CommonUtils.getIntParameter("id", request);
			HreCompensation tmp = baseService.getPojo(id, HreCompensation.class);
			
			if (tmp == null) {
				beanForm.setMessage(StringConstants.BLANK);
				initFormBean(beanForm);
				return mapping.findForward(ACTION_NAME);
			}
			
			beanForm.setId(id);
			beanForm.setYear(tmp.getYear() + "");
			beanForm.setMonth(tmp.getMonth());
			beanForm.setAmount(String.format("%15.2f", tmp.getAmount()).trim());
			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		String message = validateForm(beanForm);
		if(!StringUtils.isBlank(message)){
			beanForm.setMessage(message);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		HreCompensation tmp = baseService.getPojo(beanForm.getId(), HreCompensation.class);
		if (tmp == null) {
			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		tmp.setId(beanForm.getId());
		tmp.setMonth(beanForm.getMonth());
		tmp.setYear(CommonUtils.parseInt(beanForm.getYear(), 0));
		tmp.setAmount(Double.parseDouble(beanForm.getAmount()));
		tmp.setDateModified(new Date());

		boolean status = baseService.saveOrUpdate(tmp);
		if (!status) {
			beanForm.setMessage(StringConstants.UPDATE_FAILURE_MESSAGE);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		response.getWriter().write(StringConstants.POP_UP_CLOSE_SCRIPT);
		return null;
	}
	
	private String validateForm (CompensationUpdateForm beanForm) {
		
		if(StringUtils.isBlank(CommonUtils.normalizeString(beanForm.getAmount()))){
			return "Compensation amount cannot be blank!";
		}
		
		try {
			
			int year = Integer.parseInt(beanForm.getYear());
			if (year < 0) {
				return "Year must be a non-negative integer!";
			}
		} catch (Exception e) {
			return "Year must be an integer!"; 
		}
		
		try {
			
			double amount = Double.parseDouble(beanForm.getAmount());
			if (amount < 0) {
				return "Compensation amount must be greater than or equal to 0!";
			}
		} catch (Exception e) {
			return "Compensation amount must be a real number!";
		}

		return StringConstants.BLANK;
	}
	
	private void initFormBean(CompensationUpdateForm beanForm) {

		beanForm.setAllMonths(ComboBoxInit.getAllMonths(false));
	}
}
